package com.xxq.semester.service.impl.exam;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxq.semester.entity.exam.StudentAnswers;
import com.xxq.semester.entity.exam.StudentExam;
import com.xxq.semester.mapper.StudentAnswersMapper;
import com.xxq.semester.mapper.StudentExamMapper;
import com.xxq.semester.service.exam.IStudentAnswersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@Service
public class StudentAnswersServiceImpl extends ServiceImpl<StudentAnswersMapper, StudentAnswers> implements IStudentAnswersService {

    @Autowired
    private StudentExamMapper studentExamMapper;

    @Override
    public void submitAnswer(Integer studentId, Integer examId, Integer questionId, String answer) {
        StudentAnswers studentAnswer = new StudentAnswers();
        studentAnswer.setStudentId(studentId);
        studentAnswer.setExamId(examId);
        studentAnswer.setQuestionId(questionId);
        studentAnswer.setAnswer(answer);
        studentAnswer.setSubmittedAt(java.time.LocalDateTime.now());
        // 明确设置为 null，等待AI批阅

        studentAnswer.setIsCorrect(null);

        this.save(studentAnswer);
    }    @Override
    public void submitAnswers(Integer studentId, Integer examId, java.util.List<IStudentAnswersService.AnswerSubmission> answers) {
        java.util.List<StudentAnswers> studentAnswersList = new java.util.ArrayList<>();

        for (IStudentAnswersService.AnswerSubmission answerSubmission : answers) {
            StudentAnswers studentAnswer = new StudentAnswers();
            studentAnswer.setStudentId(studentId);
            studentAnswer.setExamId(examId);
            studentAnswer.setQuestionId(answerSubmission.getQuestionId());
            studentAnswer.setAnswer(answerSubmission.getAnswer());
            studentAnswer.setSubmittedAt(java.time.LocalDateTime.now());
            // 明确设置为 null，等待AI批阅
//            studentAnswer.setScore(null);
            studentAnswer.setIsCorrect(null);

            studentAnswersList.add(studentAnswer);
        }

        // 批量保存学生答案
        this.saveBatch(studentAnswersList);
        
        // 更新student_exam表中的状态为"completed"
        UpdateWrapper<StudentExam> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("student_id", studentId)
                    .eq("exam_id", examId)
                    .set("status", "completed");
        studentExamMapper.update(null, updateWrapper);
    }
}
